from django.shortcuts import render
from django.http import HttpResponse

from blog.models import Article

# 引入分页组件
from django.core.paginator import Paginator

# Create your views here.


def hello_world(request):
    return HttpResponse('hello world!')


def get_index_page(request):

    all_article = Article.objects.all()
    # - 表示倒序排序
    top3_article_list = Article.objects.order_by('-publish_date')[:3]

    page = request.GET.get('page')
    if page:
        page = int(page)
    else:
        # 赋一个默认值
        page = 1

    # 实例化分页组件
    # 传入文章列表和分页数量
    paginator = Paginator(all_article, 2)
    # 获取分页数
    page_num = paginator.num_pages
    # 获取当前页
    page_article_list = paginator.page(page)
    # 判断是否有下一页
    if page_article_list.has_next():
        next_page = page + 1
    else:
        next_page = page
    # 判断是否有上一页
    if page_article_list.has_previous():
        previous_page = page - 1
    else:
        previous_page = page

    # 渲染模板数据返回
    return render(request, 'blog/index.html', {
        'article_list': page_article_list,
        'page_num': range(1, page_num + 1),
        'current_page': page,
        'previous': previous_page,
        'next': next_page,
        'top3_article_list': top3_article_list
    })


def get_detail_page(request, article_id):
    # current_article = Article.objects.get(article_id=article_id)
    current_article = None
    previous_article = None
    next_article = None
    all_article = Article.objects.all()
    # previous_index = 0
    # next_index = 0
    for index, article in enumerate(all_article):
        if index == 0:
            previous_index = 0
            next_index = index + 1
        elif index == len(all_article) - 1:
            previous_index = index - 1
            next_index = index
        else:
            previous_index = index - 1
            next_index = index + 1

        if article.article_id == article_id:
            current_article = article
            previous_article = all_article[previous_index]
            next_article = all_article[next_index]

    section_list = current_article.content.split('\n')
    return render(request, 'blog/detail.html', {
        'current_article': current_article,
        'section_list': section_list,
        'previous_article': previous_article,
        'next_article': next_article
    })
